package com.itboye.core.object;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import org.json.JSONException;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;

import com.itboye.core.alert.ByAlert;
import com.itboye.core.alert.LoadingDialog;
import com.itboye.mengwu.app.MainApplication;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.ALIAS_TYPE;
import com.umeng.message.PushAgent;
import com.umeng.message.UmengRegistrar;
import com.umeng.message.proguard.k.e;

/**
 * @author hebidu 2016-4-25 wushunhui修改版
 *         继承该类不需要自己寻找控件，不需要自己写oncreate(),只需要重写里面的抽象方法即可
 */
@SuppressLint("NewApi")
public abstract class BaseActivity extends FragmentActivity {

	public static final String EVENT_TYPE_UNKNOWN = BaseActivity.class
			.getName() + "_unknown";
	View statusBar;
	LoadingDialog progressDialog = null;
	private PushAgent mPushAgent;

	@SuppressLint("ResourceAsColor")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(initView());// 设置布局
		progressDialog = new LoadingDialog();
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			Window window = getWindow();
			// Translucent status bar
			window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

			statusBar = new View(this);
			ViewGroup.LayoutParams param = new ViewGroup.LayoutParams(
					ViewGroup.LayoutParams.MATCH_PARENT, getStatusBarHeight());
			statusBar.setLayoutParams(param);
			// setStatusBarColor(R.color.main_color);
			this.addContentView(statusBar, param);

			// App.getInstance().addActivity(this);

		}
		// 判断当前SDK版本号，如果是4.4以上，就是支持沉浸式状态栏的
		if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
			getWindow().addFlags(
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			getWindow().addFlags(
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
		}
		mPushAgent=PushAgent.getInstance(this);
		mPushAgent.onAppStart();//推送开始
		smartInject();// 自动获取控件
		onMyCreate();

	}

	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	public void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	protected int getStatusBarHeight() {
		int result = 0;
		int resourceId = getResources().getIdentifier("status_bar_height",
				"dimen", "android");
		if (resourceId > 0) {
			result = getResources().getDimensionPixelSize(resourceId);
		}
		return result;
	}

	/**
	 * @param data
	 * @return 2016-4-23 hebidu
	 */
	public ResultEntity handlerError(Object data) {
		ResultEntity result = (ResultEntity) data;
		if (result == null) {
			result = new ResultEntity("-1", "数据格式错误!~", data);
			return result;
		}

		if (result.hasError()) {
			ByAlert.alert(result.getMsg());
			result.setEventType(EVENT_TYPE_UNKNOWN);
			return result;
		}

		return result;
	}

	/**
	 * 设置状态栏颜色，
	 * 
	 * @param color
	 *            颜色资源id， 如 R.color.orange</br> 0 黑色
	 */
	protected void setStatusBarColor(int color) {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			if (color == 0) {
				statusBar.setBackgroundColor(Color.BLACK);
			} else {
				statusBar.setBackgroundColor(getResources().getColor(color));
			}

		}
	}

	/**
	 * @param 2016-4-25 wushunhui
	 */
	private void smartInject() {

		try {
			Class<? extends Activity> clz = getClass();

			while (clz != BaseActivity.class) {

				Field[] fs = clz.getDeclaredFields();
				Resources res = getResources();
				String packageName = getPackageName();
				System.out.println("packageName" + packageName);
				for (Field field : fs) {

					System.out.println("field.getType()" + field.getType());
					if (!View.class.isAssignableFrom(field.getType())) {
						continue;
					}
					System.out.println("field.getName()" + field.getName());

					int viewId = res.getIdentifier(field.getName(), "id",
							packageName);
					System.out.println("viewId" + viewId);
					if (viewId == 0)
						continue;
					field.setAccessible(true);
					try {
						View v = findViewById(viewId);
						field.set(this, v);
						Class<?> c = field.getType();
						Method m = c.getMethod("setOnClickListener",
								android.view.View.OnClickListener.class);
						m.invoke(v, this);
					} catch (Throwable e) {
					}
					field.setAccessible(false);

				}

				clz = (Class<? extends Activity>) clz.getSuperclass();

			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * @author liutiantian 返回当前程序版本名
	 */
	public static String getAppVersionName(Context context) {
		String versionName = "";
		String vsersionNmae = "";
		try {
			// ---get the package info---
			PackageManager pm = context.getPackageManager();
			PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
			versionName = pi.versionName;

			if (versionName == null || versionName.length() <= 0) {
				return "";
			}
		} catch (Exception e) {
			Log.e("VersionInfo", "Exception", e);
		}
		return versionName;
	}

	/***
	 * 所有继承BaseActivity所要调用的方法
	 * 
	 * @return
	 */
	public abstract int initView();// 初始化控件及其他

	public abstract void onMyCreate();// 初始化数据相当于oncreate

	/**
	 * 显示进度对话框,带有消息 flag 是否可以取消
	 */
	@SuppressLint("NewApi")
	public void showProgressDialog(String message, boolean flag) {
		if (progressDialog == null)
			return;
		setProgressDialogMessage(message);

		progressDialog.show(getFragmentManager(), message);
		progressDialog.setCancelable(flag);

	}

	/**
	 * 设置进度对话框消息
	 * 
	 * @param message
	 */
	public void setProgressDialogMessage(String message) {
		progressDialog.setMsg(message);
	}

	/**
	 * 关闭进度对话框
	 */
	@SuppressLint("NewApi")
	public void closeProgressDialog() {
		if (progressDialog != null) {
//			if (progressDialog.getDialog().isShowing()) {
				progressDialog.dismiss();
//			}
		}
	}

}
